package com.ecnu.system.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.ecnu.common.core.domain.AjaxResult;
import com.ecnu.common.core.domain.entity.SysUser;
import com.ecnu.common.core.domain.model.LoginUser;
import com.ecnu.common.core.page.PageDomain;
import com.ecnu.common.utils.PageUtils;
import com.ecnu.common.utils.uuid.IdUtils;
import com.ecnu.system.domain.*;
import com.ecnu.system.domain.dto.ProReviewDTO;
import com.ecnu.system.domain.vo.ProReviewVO;
import com.ecnu.system.domain.vo.ProjectViewVO;
import com.ecnu.system.mapper.*;
import com.ecnu.system.service.IEmailService;
import com.ecnu.system.service.IProjectReviewService;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;

@Service
public class ProjectReviewServiceImpl extends ServiceImpl<ProjectReviewMapper, ProjectReview> implements IProjectReviewService {
    @Autowired
    private ProjectReviewMapper projectReviewMapper;
    @Autowired
    private ProjectRangeMapper projectRangeMapper;
    @Autowired
    private SysUserMapper sysUserMapper;
    @Autowired
    private ProjectMapper projectMapper;
    @Autowired
    private ProjectMessageMapper projectMessageMapper;
    @Autowired
    private IEmailService emailService;

    protected void startPage(PageDomain pageDomain) {
        PageUtils.startPage(pageDomain);
    }

    protected String getId() {
        return IdUtils.fastSimpleUUID();
    }

    @Override
    public AjaxResult saveByProId(Project project, LoginUser loginUser) {
        LambdaQueryWrapper<ProjectReview> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(ProjectReview::getProId, project.getId());
        wrapper.eq(ProjectReview::getReviewStatus, "0");
        ProjectReview review = projectReviewMapper.selectOne(wrapper);
        if (review != null) {
            return AjaxResult.error("该活动已提交审核，请耐心等待");
        }
        ProjectRange projectRange = projectRangeMapper.selectById(project.getIsRange());
        if (projectRange == null) {
            return AjaxResult.error("可见范围有误，请联系管理员");
        }
        ProjectReview projectReview = new ProjectReview();
        projectReview.setId(getId());
        projectReview.setProId(project.getId());
        projectReview.setProRange(project.getIsRange());
        projectReview.setRangeName(projectRange.getName());
        projectReview.setCreateUser(String.valueOf(loginUser.getUserId()));
        projectReview.setCreateDept(String.valueOf(loginUser.getDeptId()));
        int insert = projectReviewMapper.insert(projectReview);
        if (insert == 1) {
            /**
             * 需要添加代办处理,消息通知
             */
            new Thread(() -> {
                ProjectMessage projectMessage = new ProjectMessage();
                projectMessage.setId(getId());
                projectMessage.setSuperId(project.getId());
                projectMessage.setTitle("您好，活动【" + project.getProName() + "】 已提交可见范围修改申请，请点击跳转审核");
                projectMessage.setDeptId(project.getIsRange().equals("3")?"All":String.valueOf(loginUser.getDeptId()));//String.valueOf(loginUser.getDeptId())
                projectMessage.setType("2");
                projectMessage.setStatus("0");
                projectMessage.setCreateUser(String.valueOf(loginUser.getUserId()));
                projectMessage.setCreateName(loginUser.getUser().getNickName());
                projectMessageMapper.insert(projectMessage);
            }).start();
            new Thread(() -> {//通知
                ProjectMessage projectMessage = new ProjectMessage();
                projectMessage.setId(getId());
                projectMessage.setSuperId(project.getId());
                projectMessage.setTitle("您好，您发起的活动【" + project.getProName() + "】 可见范围修改申请已发起成功");
                projectMessage.setDeptId(project.getIsRange().equals("3")?"All":String.valueOf(loginUser.getDeptId()));//String.valueOf(loginUser.getDeptId())
                projectMessage.setType("1");
                projectMessage.setStatus("0");
                projectMessage.setCreateName(loginUser.getUser().getNickName());
                projectMessage.setCreateUser(String.valueOf(loginUser.getUserId()));
                projectMessageMapper.insert(projectMessage);
            }).start();

            //推送审核邮件
            emailService.ReviewEmail(project,loginUser);

            return AjaxResult.success("添加成功");
        } else {
            return AjaxResult.error("添加失败");
        }
    }

    @Override
    public AjaxResult updateByProId(ProReviewDTO dto, Project project, LoginUser loginUser) {
        //审核记录
        ProjectReview projectReview = new ProjectReview();
        BeanUtils.copyProperties(dto, projectReview);
        projectReview.setReviewUser(String.valueOf(loginUser.getUserId()));
        int update = projectReviewMapper.updateById(projectReview);
        if (update == 1) {
            SysUser sysUser = sysUserMapper.selectUserById(Long.valueOf(project.getCreateUser()));
            if ("1".equals(dto.getReviewStatus())){
                //更新项目可见范围
                Project projectDto = new Project();
                projectDto.setId(dto.getProId());
                projectDto.setRangeType(project.getIsRange().equals("3") ? "All" : String.valueOf(sysUser.getDeptId()));
                projectMapper.updateById(projectDto);
            }
            //处理代办
            new Thread(() -> {//待办状态调整
                ProjectMessage projectMessage = new ProjectMessage();
//                projectMessage.setId(getId());
                projectMessage.setSuperId(project.getId());
                projectMessage.setStatus("1");
                projectMessage.setUpdateUser(String.valueOf(loginUser.getUserId()));
                projectMessage.setUpdateName(loginUser.getUser().getNickName());
                projectMessageMapper.updateBySuperId(projectMessage);
            }).start();
            new Thread(() -> {//通知
                ProjectMessage projectMessage = new ProjectMessage();
                projectMessage.setId(getId());
                projectMessage.setSuperId(project.getId());
                projectMessage.setTitle("您好，您发起的活动【" + project.getProName() + "】 可见范围修改申请，已由 " + loginUser.getUser().getNickName() + " 完成审核");
                projectMessage.setDeptId(String.valueOf(sysUser.getDeptId()));
                projectMessage.setType("1");
                projectMessage.setStatus("0");
                projectMessage.setCreateUser(String.valueOf(sysUser.getUserId()));
                projectMessage.setCreateName(sysUser.getNickName());
                projectMessage.setUpdateName(loginUser.getUser().getNickName());
                projectMessage.setUpdateUser(String.valueOf(loginUser.getUserId()));
                projectMessageMapper.insert(projectMessage);
            }).start();
            // 推送审核完成邮件
             emailService.ReviewCompletedEmail(project,dto.getReviewStatus());
            return AjaxResult.success("审核成功");
        } else {
            log.error("审核失败" + projectReview.getId());
            return AjaxResult.error("审核失败");
        }
    }

    @Override
    public List<ProjectViewVO> selectList(LoginUser loginUser, String pageDomain) {
        try {
            ProjectReview review = new ProjectReview();
            if (loginUser.getUser().getRoles().get(0).getRoleId().equals(103L)) {
                review.setProRange("2");
                review.setCreateDept(String.valueOf(loginUser.getDeptId()));
            }else if (loginUser.getUser().getRoles().get(0).getRoleId().equals(1L) || loginUser.getUser().getRoles().get(0).getRoleId().equals(2L)) {
                review.setProRange("3");
            } else {
                return new ArrayList<>();
            }
//            startPage(pageDomain.get);
            List<ProjectViewVO> projectReviews = projectReviewMapper.selectByList(review, pageDomain);
            return projectReviews;
        } catch (Exception e) {
            log.error("查询失败" + e.getMessage());
            return new ArrayList<>();
        }
    }

    @Override
    public AjaxResult selectReviewInfo(String id, String proId) {
        QueryWrapper<ProjectReview> wrapper = new QueryWrapper<>();
        wrapper.eq("id", id);
        ProjectReview review = projectReviewMapper.selectOne(wrapper);
        if (review != null) {
            ProReviewVO proReviewVO = new ProReviewVO();
            BeanUtils.copyProperties(review, proReviewVO);
            if (proReviewVO.getReviewStatus().equals("1")) {
                proReviewVO.setStatusName("通过");
            } else if (proReviewVO.getReviewStatus().equals("2")) {
                proReviewVO.setStatusName("未通过");
            } else {
                proReviewVO.setStatusName("待审核");
            }
            return AjaxResult.success(proReviewVO);
        }
        return AjaxResult.error("报名信息不存在");
    }

    @Override
    public AjaxResult selectInfo(String id) {
        QueryWrapper<ProjectReview> wrapper = new QueryWrapper<>();
        wrapper.eq("pro_id", id);
        wrapper.orderByDesc("create_time");

        List<ProjectReview> list = projectReviewMapper.selectList(wrapper);
        if (list != null && !list.isEmpty()) {
            ProjectReview review = list.get(0);
            ProReviewVO proReviewVO = new ProReviewVO();
            BeanUtils.copyProperties(review, proReviewVO);
            if (proReviewVO.getReviewStatus().equals("1")) {
                proReviewVO.setStatusName("通过");
            } else if (proReviewVO.getReviewStatus().equals("2")) {
                proReviewVO.setStatusName("未通过");
            } else {
                proReviewVO.setStatusName("待审核");
            }
            return AjaxResult.success(proReviewVO);

        }
        return AjaxResult.success(new ProReviewVO());
    }

    @Override
    public List<ProjectViewVO> mySubmissionList(LoginUser loginUser, String name) {
        List<ProjectViewVO> projectReviews = projectReviewMapper.selectSubmissionList(loginUser.getUserId(), name);
        return projectReviews;
    }
}
